package com.sinoatma.physignsmonitor.fragment


import android.content.Intent
import android.net.Uri
import android.os.AsyncTask
import android.os.Handler
import android.os.Looper
import android.util.Log
import android.widget.Toast
import androidx.core.content.FileProvider
import androidx.lifecycle.Observer
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.common.frame.base.BaseFragment
import com.common.frame.extension.setSingleClick
import com.scwang.smartrefresh.layout.api.RefreshLayout
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadmoreListener
import com.sinoatma.physignsmonitor.R
import com.sinoatma.physignsmonitor.adapter.HistoryAdapter
import com.sinoatma.physignsmonitor.adapter.HistoryOffAdapter
import com.sinoatma.physignsmonitor.bean.BloodCollectListBean
import com.sinoatma.physignsmonitor.bean.MonitorRecordEntity
import com.sinoatma.physignsmonitor.constant.ModeFlag
import com.sinoatma.physignsmonitor.constant.baseIp
import com.sinoatma.physignsmonitor.constant.currentModel
import com.sinoatma.physignsmonitor.databinding.FragmentHistoryListBinding
import com.sinoatma.physignsmonitor.view.DialogOnlineOfflineSwitchUtil
import com.sinoatma.physignsmonitor.view.DialogUtil
import com.sinoatma.physignsmonitor.view.LoadProgressDialog
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import okhttp3.OkHttpClient
import okhttp3.Request
import java.io.File
import java.io.FileOutputStream
import java.io.InputStream


/**
 * 历史列表
 */
class HistoryListFragment : BaseFragment<HistoryListViewModel,FragmentHistoryListBinding>() {
    override fun layoutId(): Int =R.layout.fragment_history_list

    lateinit var adapter: HistoryAdapter
    lateinit var adapterOff: HistoryOffAdapter
    lateinit var loadProgressDialog: LoadProgressDialog
    var page=1

    var historyListOff = ArrayList<MonitorRecordEntity>()
    var historyList = arrayListOf<BloodCollectListBean>()
    val handler = Handler(Looper.getMainLooper())
    override fun initData() {
        if (currentModel==3){
            if (ModeFlag==0){
                adapterOff=HistoryOffAdapter(historyListOff)
                binding.historyRecycler.adapter=adapterOff
            }else{
                adapter=HistoryAdapter(historyList)
                binding.historyRecycler.adapter=adapter
            }
        }else{
            if (currentModel==0){
                adapterOff=HistoryOffAdapter(historyListOff)
                binding.historyRecycler.adapter=adapterOff
            }else{
                adapter=HistoryAdapter(historyList)
                binding.historyRecycler.adapter=adapter
            }
        }

        binding.historyRecycler.layoutManager=LinearLayoutManager(requireActivity())


    }

    override fun initView() {
        loadProgressDialog = LoadProgressDialog(requireActivity())
    }

    override fun onResume() {
        super.onResume()
        if (currentModel==3){
            if (ModeFlag==0){
                page=0
                queryHistoryData()
            }else{
                if (historyList.isEmpty()){
                    refresh()
                }
            }
        }else{
            if (currentModel==0){
                page=0
                queryHistoryData()
            }else{
                if (historyList.isEmpty()){
                    refresh()
                }
            }
        }
    }

    override fun initListener() {
        super.initListener()
        binding.tvSwModel.setSingleClick {
//            queryHistoryData()
            DialogOnlineOfflineSwitchUtil.showCustomDialogWithCountdown(
                requireActivity(),
                DialogOnlineOfflineSwitchUtil.DialogType.INFO,
                onPositiveButtonClick = {
                    // 联网模式
                    currentModel=1
                    initData()
                    refresh()
                },
                onNegativeButtonClick = {
                    // 离线模式
                    currentModel=0
                    initData()
                    refresh()

                }
            )
        }


        if (currentModel==3){
            if(ModeFlag==0){
                adapterOff.setOnItemClickListener { adapter, view, position ->
                    viewModel.initExcelFolder()
//                Log.e("zsy","${baseIp}${historyList[position].filePath}")
                    if (historyListOff[position].fileAddress.isEmpty()){
                        Toast.makeText(requireContext(),"文件路径错误，请重试!",Toast.LENGTH_LONG).show()
                        return@setOnItemClickListener
                    }
//            loadProgressDialog.setMessage("正在开启文件，清稍等...")
                    lifecycleScope.launch(Dispatchers.IO) {
//                    DownloadFileTask("${baseIp}/bdms/${historyListOff[position].fileAddress}", viewModel.filePath).execute()
                        withContext(Dispatchers.Main) {
                            loadProgressDialog.dismiss()
                            val excelFile = File(historyListOff[position].fileAddress)
                            if (excelFile.exists()) {
                                val intent = Intent(Intent.ACTION_VIEW)
                                val uri: Uri = FileProvider.getUriForFile(requireActivity(), "com.sinoatma.physignsmonitor.provider", excelFile)
                                intent.setDataAndType(uri, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
                                intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION) // Grant read permission to other apps
                                // 使用 createChooser 强制弹出应用选择框
                                val chooser = Intent.createChooser(intent, "选择查看方式")
                                startActivity(chooser)
                            }
                        }
                    }
                }
            }else{
                adapter.setOnItemClickListener { adapter, view, position ->
                    viewModel.initExcelFolder()
                    Log.e("zsy","${baseIp}${historyList[position].filePath}")
                    if (historyList[position].filePath.isEmpty()){
                        Toast.makeText(requireContext(),"文件路径错误，请重试!",Toast.LENGTH_LONG).show()
                        return@setOnItemClickListener
                    }
//            loadProgressDialog.setMessage("正在开启文件，清稍等...")
                    lifecycleScope.launch(Dispatchers.IO) {
                        DownloadFileTask("${baseIp}/bdms/${historyList[position].filePath}", viewModel.filePath).execute()
                        withContext(Dispatchers.Main) {
                            loadProgressDialog.dismiss()
                            val excelFile = File(viewModel.filePath)
                            if (excelFile.exists()) {
                                val intent = Intent(Intent.ACTION_VIEW)
                                val uri: Uri = FileProvider.getUriForFile(requireActivity(), "com.sinoatma.physignsmonitor.provider", excelFile)
                                intent.setDataAndType(uri, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
                                intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION) // Grant read permission to other apps
                                // 使用 createChooser 强制弹出应用选择框
                                val chooser = Intent.createChooser(intent, "选择查看方式")
                                startActivity(chooser)
                            }
                        }
                    }
                }
            }
        }else{
            if(currentModel==0){
                adapterOff.setOnItemClickListener { adapter, view, position ->
                    viewModel.initExcelFolder()
//                Log.e("zsy","${baseIp}${historyList[position].filePath}")
                    if (historyListOff[position].fileAddress.isEmpty()){
                        Toast.makeText(requireContext(),"文件路径错误，请重试!",Toast.LENGTH_LONG).show()
                        return@setOnItemClickListener
                    }
//            loadProgressDialog.setMessage("正在开启文件，清稍等...")
                    lifecycleScope.launch(Dispatchers.IO) {
//                    DownloadFileTask("${baseIp}/bdms/${historyListOff[position].fileAddress}", viewModel.filePath).execute()
                        withContext(Dispatchers.Main) {
                            loadProgressDialog.dismiss()
                            val excelFile = File(historyListOff[position].fileAddress)
                            if (excelFile.exists()) {
                                val intent = Intent(Intent.ACTION_VIEW)
                                val uri: Uri = FileProvider.getUriForFile(requireActivity(), "com.sinoatma.physignsmonitor.provider", excelFile)
                                intent.setDataAndType(uri, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
                                intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION) // Grant read permission to other apps
                                // 使用 createChooser 强制弹出应用选择框
                                val chooser = Intent.createChooser(intent, "选择查看方式")
                                startActivity(chooser)
                            }
                        }
                    }
                }
            }else{
                adapter.setOnItemClickListener { adapter, view, position ->
                    viewModel.initExcelFolder()
                    Log.e("zsy","${baseIp}${historyList[position].filePath}")
                    if (historyList[position].filePath.isEmpty()){
                        Toast.makeText(requireContext(),"文件路径错误，请重试!",Toast.LENGTH_LONG).show()
                        return@setOnItemClickListener
                    }
//            loadProgressDialog.setMessage("正在开启文件，清稍等...")
                    lifecycleScope.launch(Dispatchers.IO) {
                        DownloadFileTask("${baseIp}/bdms/${historyList[position].filePath}", viewModel.filePath).execute()
                        withContext(Dispatchers.Main) {
                            loadProgressDialog.dismiss()
                            val excelFile = File(viewModel.filePath)
                            if (excelFile.exists()) {
                                val intent = Intent(Intent.ACTION_VIEW)
                                val uri: Uri = FileProvider.getUriForFile(requireActivity(), "com.sinoatma.physignsmonitor.provider", excelFile)
                                intent.setDataAndType(uri, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
                                intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION) // Grant read permission to other apps
                                // 使用 createChooser 强制弹出应用选择框
                                val chooser = Intent.createChooser(intent, "选择查看方式")
                                startActivity(chooser)
                            }
                        }
                    }
                }
            }
        }




        binding.smartRefreshLayout.setOnRefreshLoadmoreListener(object :OnRefreshLoadmoreListener{
            override fun onRefresh(refreshlayout: RefreshLayout) {
                //下拉刷新
//                loadProgressDialog.setMessage("数据加载中,请稍等...")
                refresh()
                // 延迟指定时间后关闭刷新状态
                // 使用 Handler 延迟指定时间后关闭刷新状态
                handler.postDelayed({
                    refreshlayout.finishRefresh()
                }, 3000)
            }

            override fun onLoadmore(refreshlayout: RefreshLayout) {
                //上拉加载
                if (historyList.size>=30){
//                    loadProgressDialog.setMessage("数据加载中,请稍等...")
                    loadMore()
                }else{
                    binding.smartRefreshLayout.finishLoadmore()
                }
                handler.postDelayed({
                    refreshlayout.finishLoadmore()
                }, 3000)
            }
        })
    }

    fun  refresh(){
       if (currentModel==3){
           if(ModeFlag==0){
               page=0
               queryHistoryData()
           }else{
               page=1
               viewModel.bloodCollectList(page)
           }
       }else{
           if(currentModel==0){
               page=0
               queryHistoryData()
           }else{
               page=1
               viewModel.bloodCollectList(page)
           }
       }

    }

    fun loadMore(){
       if (currentModel==3){
           if(ModeFlag==0){
               page+=1
               queryHistoryData()
               binding.smartRefreshLayout.finishLoadmore()
           }else{
               page+=1
               viewModel.bloodCollectList(page)
           }
       }else{
           if(currentModel==0){
               page+=1
               queryHistoryData()
               binding.smartRefreshLayout.finishLoadmore()
           }else{
               page+=1
               viewModel.bloodCollectList(page)
           }
       }
    }

    override fun initObserve() {
        super.initObserve()
        viewModel.dataList.observe(this, Observer {
//            loadProgressDialog.dismiss()
            if (page==1){
                binding.smartRefreshLayout.finishRefresh()
                historyList.clear()
                historyList.addAll(it)
                adapter.notifyDataSetChanged()
            }else{
                binding.smartRefreshLayout.finishLoadmore()
                historyList.addAll(it)
                adapter.notifyDataSetChanged()
            }
        })
        viewModel.dataMsg.observe(this, Observer {
            loadProgressDialog.dismiss()
            if (page==0){
                binding.smartRefreshLayout.finishRefresh()
            }else{
                binding.smartRefreshLayout.finishLoadmore()
            }
        })

    }

    fun queryHistoryData(){
        viewModel.getRecordsByPage(page, 20).observe(this, Observer { records ->
            // 更新UI，如显示在RecyclerView中
            records?.let {
                // 在这里更新UI（比如 RecyclerView）
                Log.e("zsy","集合数据${it}")
                if (historyListOff.size<20){
                    historyListOff.clear()
                    historyListOff.addAll(it)
                    adapterOff.notifyDataSetChanged()
                }else{
                    historyListOff.addAll(it)
                    adapterOff.notifyDataSetChanged()
                }
                if (page==0){
                    binding.smartRefreshLayout.finishRefresh()
                }else{
                    binding.smartRefreshLayout.finishLoadmore()
                }


            }
        })
    }



    class DownloadFileTask(private val url: String, private val filePath: String) :
        AsyncTask<Void, Void, Boolean>() {
        override fun doInBackground(vararg params: Void?): Boolean {
            val client = OkHttpClient()
            val request = Request.Builder()
                .url(url)
                .build()
            try {
                val response = client.newCall(request).execute()
                if (response.isSuccessful) {
                    val inputStream: InputStream? = response.body?.byteStream()
                    val outputStream = FileOutputStream(File(filePath))
                    inputStream?.use { input ->
                        outputStream.use { output ->
                            input.copyTo(output)
                        }
                    }
                    return true
                }
            } catch (e: Exception) {
                e.printStackTrace()
            }
            return false
        }
    }



}